from calm.evaluator import Evaluator
from system.gameServer import gameServer

import yaml

class PicEvaluator(Evaluator):
    def __init__(self, server, vars):
        self.filename = None
        self.activeColor = (1,0,0)
        self.inactiveColor = (1,1,1)
        self.allowSharing = True
        
        Evaluator.__init__(self, server, vars)
        
        fp = open(self.filename,"r")
        assert fp, "invalid pic filename %s" % self.filename
        
        data = yaml.evalLoad(fp)
        
        self.w = data['width']
        self.h = data['height']
        self.pixels = map(tuple,data['pixels'])
        self.filledPixels = []
        
        self.gfx = self.server.addChild("gui.menu","picEvaluatorGfx")
        self.gfx.setVar("layer",1)
        
        self.gfxPixels = {}
        self.pixelw = 1.0 / float(self.w)
        self.pixelh = 1.0 / float(self.h)
        for i in range(self.w):
            for j in range(self.h):
                
                if (i,j) in self.pixels:
                    pixel = self.gfx.addChild("pixel")
                    pixel.setVar("color",self.inactiveColor)
                    
                    pixel.setVar("pos",(self.pixelw*i+0.005,self.pixelh*j+0.005))
                    pixel.setVar("scale",(self.pixelw-0.01,self.pixelh-0.01))
                    pixel.setVar("filled",False)
                    pixel.setVar("renderOp2d","rect")
                    
                    #outline = pixel.addChild("outline")
                    #outline.setVar("renderOp2d","rect")
                    #outline.setVar("filled",False)
                    
                    self.gfxPixels[(i,j)] = pixel
                    
    def evaluate(self, agent):
        fitness = 0
        self.filledPixels = []
        
        for agentPos in self.server.evalMap.values():
            agent = self.server.agents[agentPos]
            x,y = agent.getVar("pos")
            i,j = int(x / float(gameServer.screenw) / self.pixelw), int(y / float(gameServer.screenh) / self.pixelh)
            #print "agent", i, "pos", (x,y), "pixel", (i,j), "ok", (i,j) in self.pixels
            if i >= 0 and i < self.w and j >= 0 and j < self.h:
                if (i,j) in self.pixels and (i,j) not in self.filledPixels:
                    #print "agent", agentPos, "got pixel", (i,j)
                    fitness += 1
                    if not self.allowSharing:
                        self.filledPixels.append((i,j))
        
        return fitness
